package agency.tango.materialintroscreen;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import agency.tango.materialintroscreen.parallax.ParallaxComponentContainer;
import ohos.agp.components.Component;
import ohos.agp.components.Image;
import ohos.agp.components.LayoutScatter;
import ohos.agp.components.Text;
import ohos.app.Context;
import ohos.bundle.IBundleManager;
import ohos.global.resource.NotExistException;
import ohos.global.resource.WrongTypeException;
import ohos.utils.PacMap;

import org.jetbrains.annotations.NotNull;

import agency.tango.materialintroscreen.utils.LogUtil;


/**
 * @ProjectName: material-intro-screen-master
 * @Package: agency.tango.materialintroscreen
 * @ClassName: SlideComponentContainer
 * @Description: pageslider的item基类
 * 封装了背景色的获取及设置 title的文字获取及设置
 * messagebutton的背景色获取及设置 description的文字获取及设置 权限的申请及判断
 * @CreateDate: 2021/4/12 20:03
 * @UpdateDate: 2021/4/12 20:03
 * @UpdateRemark: 暂无
 * @Version: 1.0
 */
public class SlideComponentContainer extends ParallaxComponentContainer {
    private static final String BACKGROUND_COLOR = "background_color";
    private static final String BUTTONS_COLOR = "buttons_color";
    private static final String TITLE = "title";
    private static final String DESCRIPTION = "description";
    private static final String NEEDED_PERMISSIONS = "needed_permission";
    private static final String POSSIBLE_PERMISSIONS = "possible_permission";
    private static final String IMAGE = "image";
    private static final int PERMISSIONS_REQUEST_CODE = 15621;
    private static final PacMap BUNDLE = new PacMap();

    private int backgroundColor;
    private int buttonsColor;
    private int image;
    private String title;
    private String description;
    private String[] neededPermissions;
    private String[] possiblePermissions;

    private Text titleTextView;
    private Text descriptionTextView;
    private Image imageView;

    public String getTitle() {
        return title;
    }

    public SlideComponentContainer(Context context) {
        super(context);
    }

    /**
     * 控件初始化
     *
     * @param builder SlideComponet属性builder
     * @param context 上下文
     * @return SlideComponentContainer
     */
    public static SlideComponentContainer createInstance(SlideViewBuilder builder, Context context) {
        BUNDLE.putIntValue(BACKGROUND_COLOR, builder.getBackgroundColor());
        BUNDLE.putIntValue(BUTTONS_COLOR, builder.getButtonsColor());
        BUNDLE.putIntValue(IMAGE, builder.getImage());
        BUNDLE.putString(TITLE, builder.getTitle());
        BUNDLE.putString(DESCRIPTION, builder.getDescription());
        BUNDLE.putStringArray(NEEDED_PERMISSIONS,
                builder.getNeededPermissions());
        BUNDLE.putStringArray(POSSIBLE_PERMISSIONS,
                builder.getPossiblePermissions());
        return new SlideComponentContainer(context);
    }

    private static boolean isNotNullOrEmpty(String string) {
        return string != null && !string.isEmpty();
    }


    @Override
    protected void initView() {
        if (mContext == null || mContext.get() == null) {
            return;
        }
        mRootView =
                LayoutScatter.getInstance(mContext.get()).parse(ResourceTable.Layout_fragment_slide, null, false);
        if (mRootView == null) {
            return;
        }
        titleTextView =
                (Text) mRootView.findComponentById(ResourceTable.Id_txt_title_slide);
        descriptionTextView =
                (Text) mRootView.findComponentById(ResourceTable.Id_txt_description_slide);
        imageView =
                (Image) mRootView.findComponentById(ResourceTable.Id_image_slide);
        initializeView();
    }

    private void initializeView() {
        backgroundColor = BUNDLE.getIntValue(BACKGROUND_COLOR);
        buttonsColor = BUNDLE.getIntValue(BUTTONS_COLOR);
        image = BUNDLE.getIntValue(IMAGE, 0);
        title = BUNDLE.getString(TITLE);
        description = BUNDLE.getString(DESCRIPTION);
        neededPermissions = BUNDLE.getStringArray(NEEDED_PERMISSIONS);
        possiblePermissions = BUNDLE.getStringArray(POSSIBLE_PERMISSIONS);
        updateViewWithValues();
    }

    /**
     * 获取背景颜色
     *
     * @return background颜色
     */
    public int backgroundColor() {
        return backgroundColor;
    }

    /**
     * 获取button颜色
     *
     * @return button颜色
     */
    public int buttonsColor() {
        return buttonsColor;
    }

    /**
     * 所有权限检测
     *
     * @return 是否有权限需要去申请
     */
    public boolean hasAnyPermissionsToGrant() {
        boolean hasPermissionToGrant = hasPermissionsToGrant(neededPermissions);
        if (!hasPermissionToGrant) {
            hasPermissionToGrant = hasPermissionsToGrant(possiblePermissions);
        }
        return hasPermissionToGrant;
    }

    /**
     * 必要权限检测
     *
     * @return 是否有必须要的权限需要去申请
     */
    public boolean hasNeededPermissionsToGrant() {
        return hasPermissionsToGrant(neededPermissions);
    }

    /**
     * 是否可以继续滑动
     *
     * @return 是否可以继续滑动
     */
    public boolean canMoveFurther() {
        return true;
    }

    /**
     * 获取不能继续滑动的错误信息
     *
     * @return 错误信息
     */
    public String cantMoveFurtherErrorMessage() {
        try {
            return mContext.get().getResourceManager().getElement(ResourceTable.String_impassable_slide).getString();
        } catch (IOException | NotExistException | WrongTypeException e) {
            LogUtil.error(this.getClass().getSimpleName(), e.toString());
        }
        return "";
    }

    private void updateViewWithValues() {
        titleTextView.setText(title);
        descriptionTextView.setText(description);
        if (image != 0) {
            imageView.setPixelMap(image);
            imageView.setVisibility(Component.VISIBLE);
        }
    }

    /**
     * 请求权限
     */
    public void askForPermissions() {
        ArrayList<String> notGrantedPermissions = new ArrayList<>();
        if (neededPermissions != null) {
            askNeedPermission(notGrantedPermissions);
        }
        if (possiblePermissions != null) {
            askPossiblePermission(notGrantedPermissions);
        }
        String[] permissionsToGrant =
                removeEmptyAndNullStrings(notGrantedPermissions);
        mContext.get().requestPermissionsFromUser(permissionsToGrant,
                PERMISSIONS_REQUEST_CODE);
    }

    private void askPossiblePermission(ArrayList<String> notGrantedPermissions) {
        for (String permission : possiblePermissions) {
            if (isNotNullOrEmpty(permission)) {
                if (mContext.get().verifyCallingOrSelfPermission(permission) != IBundleManager.PERMISSION_GRANTED) {
                    notGrantedPermissions.add(permission);
                }
            }
        }
    }

    private void askNeedPermission(ArrayList<String> notGrantedPermissions) {
        for (String permission : neededPermissions) {
            if (isNotNullOrEmpty(permission)) {
                if (mContext.get().verifyCallingOrSelfPermission(permission) != IBundleManager.PERMISSION_GRANTED) {
                    notGrantedPermissions.add(permission);
                }
            }
        }
    }

    private boolean hasPermissionsToGrant(String[] permissions) {
        if (permissions == null) {
            return false;
        }
        for (String permission : permissions) {
            if (isNotNullOrEmpty(permission)) {
                if (mContext.get().verifyCallingOrSelfPermission(permission) != IBundleManager.PERMISSION_GRANTED) {
                    return true;
                }
            }
        }
        return false;
    }

    private String[] removeEmptyAndNullStrings(final ArrayList<String> permissions) {
        List<String> list = new ArrayList<>(permissions);
        list.removeAll(Collections.singleton(null));
        String[] ts = new String[list.size()];
        return list.toArray(ts);
    }

    /**
     * 获取根控件
     *
     * @return mRootView
     */
    public @NotNull Component getRootView() {
        return mRootView;
    }
}
